package com.tea.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.tea.common.core.controller.BaseController;
import com.tea.common.core.domain.AjaxResult;
import com.tea.common.core.page.TableDataInfo;
import com.tea.common.utils.SecurityUtils;
import com.tea.common.utils.StringUtils;
import com.tea.funct.domain.*;
import com.tea.funct.domain.res.CodePointInfo;
import com.tea.funct.domain.res.FixationConfig;
import com.tea.funct.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @PACKAGE_NAME: com.tea.controller
 * @CLASSNAME: WxApiController
 * @DEACRIPTION: 小程序接口控制器
 * @AUTHOR: GuoChen
 * @DATE: 2024/5/27
 * @WEEK: 周一
 **/
@Slf4j
@RestController
@RequestMapping("/market")
public class WxApiController extends BaseController {

    @Autowired
    private ITeaCategoryService teaCategoryService;
    @Autowired
    private ITeaSubclassService teaSubclassService;
    @Autowired
    private ITeaProductService teaProductService;
    @Autowired
    private ITeaInformService teaInformService;
    @Autowired
    private ITeaFixationService teaFixationService;
    @Autowired
    private ITeaAdvertisConfigService teaAdvertisConfigService;

    /**
     * 获取静态配置数据信息
     *
     * @return
     */
    @GetMapping("/getFixationConfigData")
    public AjaxResult getFixationConfigData() {
        log.info("获取静态配置数据信息...");
        FixationConfig configInfo = teaFixationService.getConfigInfo();
        return AjaxResult.success(configInfo);
    }

    /**
     * 获取广告配置信息
     *
     * @return
     */
    @GetMapping("/getAdvertiseConfigKey")
    public AjaxResult getAdvertiseConfigKey() {
        log.info("获取广告配置信息...");
        TeaAdvertisConfig teaAdvertisConfig = teaAdvertisConfigService.selectActiviteTeaAdvertisConfig();
        return AjaxResult.success(teaAdvertisConfig);
    }

    /**
     * 获取小程序二维码通用的配置坐标点信息
     *
     * @return
     */
    @GetMapping("/getCommonCodePoint")
    public AjaxResult getCommonCodePoint() {
        log.info("获取小程序二维码通用的配置坐标点信息");
        CodePointInfo codePointInfo = null;
        TeaFixation teaFixation = teaFixationService.selectTeaFixationByFeild("codeAbsolutePointInfo");
        if (teaFixation != null && StringUtils.isNotBlank(teaFixation.getFixationImgConf())) {
            log.info("获取到通用的坐标配置信息为：{}", teaFixation.getFixationImgConf());
            codePointInfo = JSONUtil.toBean(teaFixation.getFixationImgConf(), CodePointInfo.class);
        }
        return AjaxResult.success(codePointInfo);
    }

    /**
     * 获取通知信息
     *
     * @return
     */
    @GetMapping("/getOneInform")
    public AjaxResult getOneInform() {
        log.info("获取通知信息");
        TeaInform inform = teaInformService.selectTeaInformOne();
        return AjaxResult.success(inform);
    }

    /**
     * 获取首页展示的数据(30条)
     *
     * @return
     */
    @GetMapping("/getIndexShowList")
    public AjaxResult getIndexShowList() {
        log.info("获取首页展示的数据");
        Long categoryIdTemp = 1l; // 默认为口粮产品
        TeaProduct teaProduct = new TeaProduct();
        // 获取是否等待审核素材
        TeaFixation teaFixation = teaFixationService.selectTeaFixationByFeild("pendingReviewMaterial");
        if (teaFixation != null) {
            // 大类名称
            String categoryName = teaFixation.getFixationImgConf();
            if (StringUtils.isNotBlank(categoryName)) {
                TeaCategory teaCategory = teaCategoryService.selectTeaCategoryByName(categoryName);
                if (teaCategory != null) {
                    categoryIdTemp = teaCategory.getId();
                }
            }
        }
        teaProduct.setCategoryId(categoryIdTemp);
        List<List<TeaProduct>> oList = new ArrayList<>();
        PageHelper.startPage(1, 30);
        List<TeaProduct> list = teaProductService.selectTeaProductList(teaProduct);
        // 首页数据10行，每行3个值
        if (list != null && list.size() > 0) {
            oList = StringUtils.splitList(list, 3);
        }
        return AjaxResult.success(oList);
    }

    /**
     * 获取所有大类信息
     *
     * @return
     */
    @GetMapping("/getCategoryList")
    public AjaxResult getCategoryList() {
        log.info("获取所有大类信息");
        List<TeaCategory> list = teaCategoryService.selectTeaCategoryListAll();
        return AjaxResult.success(list);
    }

    /**
     * 根据大类id查询小类数据
     *
     * @param categoryId 大类ID
     * @return
     */
    @GetMapping("/getSubclassByCategoryId/{categoryId}")
    public AjaxResult getSubclassByCategoryId(@PathVariable("categoryId") Long categoryId) {
        log.info("根据大类id:{} 查询小类数据", categoryId);
        TeaSubclass teaSubclass = new TeaSubclass();
        if (!SecurityUtils.isUserLogin()) {
            log.info("用户未登录, 则固定查询数据");
            Long categoryIdTemp = 1l; // 默认为口粮产品
            // 获取是否等待审核素材
            TeaFixation teaFixation = teaFixationService.selectTeaFixationByFeild("pendingReviewMaterial");
            if (teaFixation != null) {
                // 大类名称
                String categoryName = teaFixation.getFixationImgConf();
                if (StringUtils.isNotBlank(categoryName)) {
                    TeaCategory teaCategory = teaCategoryService.selectTeaCategoryByName(categoryName);
                    if (teaCategory != null) {
                        categoryIdTemp = teaCategory.getId();
                    }
                }
            }
            teaSubclass.setCategoryId(categoryIdTemp);
        } else {
            teaSubclass.setCategoryId(categoryId);
        }
        List<TeaSubclass> list = teaSubclassService.selectTeaSubclassList(teaSubclass);
        return AjaxResult.success(list);
    }

    /**
     * 根据大类、小类和产品名称查询相关产品信息
     *
     * @param categoryId  大类id
     * @param subclassId  小类id
     * @param productName 产品名称
     * @return
     */
    @GetMapping("/getProductList/{categoryId}")
    public TableDataInfo getProductList(@PathVariable("categoryId") Long categoryId,
                                        @RequestParam("pageNum") Integer pageNum,
                                        @RequestParam("pageSize") Integer pageSize,
                                        @RequestParam(value = "subclassId", required = false) Long subclassId,
                                        @RequestParam(value = "productName", required = false) String productName) {
        log.info("根据大类{}, 小类{}, 产品名称{} 查询相关产品信息", categoryId, subclassId, productName);
        TeaProduct teaProduct = new TeaProduct();
        if (!SecurityUtils.isUserLogin()) {
            log.info("用户未登录，则查询固定数据");
            Long categoryIdTemp = 1l; // 默认为口粮产品
            // 获取是否等待审核素材
            TeaFixation teaFixation = teaFixationService.selectTeaFixationByFeild("pendingReviewMaterial");
            if (teaFixation != null) {
                // 大类名称
                String categoryName = teaFixation.getFixationImgConf();
                if (StringUtils.isNotBlank(categoryName)) {
                    TeaCategory teaCategory = teaCategoryService.selectTeaCategoryByName(categoryName);
                    if (teaCategory != null) {
                        categoryIdTemp = teaCategory.getId();
                    }
                }
            }
            teaProduct.setCategoryId(categoryIdTemp);
            // startPage(1, 15);
            PageHelper.startPage(1, 15);
            List<TeaProduct> list = teaProductService.selectTeaProductList(teaProduct);
            return getDataTable(list);
        }
        Long userId = SecurityUtils.getUserId();
        teaProduct.setCategoryId(categoryId);
        teaProduct.setSubclassId(subclassId);
        teaProduct.setProductName(productName);
        PageHelper.startPage(pageNum, pageSize);
        List<TeaProduct> list = teaProductService.selectTeaProductList(teaProduct);
        if (list != null && list.size() > 0) {
            for (TeaProduct product : list) {
                TeaFocus teaFocus = teaProductService.selectFocusByProductIdAndUserId(product.getId(), userId);
                product.setFocusId(1l); // 未关注
                if (teaFocus != null) {
                    product.setFocusId(0l); // 已关注
                }
            }
        }
        return getDataTable(list);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStamp = sdf.format(new Date()); // 当前时间信息
        String signStr = timeStamp + "dEB416XmG2ZOBQKnSzrVZMFERUCAwEAAQ"; // 加密前数据
        MessageDigest md = MessageDigest.getInstance("MD5");
        //通过md5计算摘要
        byte[] bytes = md.digest(signStr.getBytes(StandardCharsets.UTF_8));
        //md5值转成可读字符串
        StringBuilder signFlag = new StringBuilder(); // 加密后数据
        for (byte b : bytes) {
            // 字节转换为32位
            signFlag.append(String.format("%02x", b));
        }
        String sign = signFlag.toString().toUpperCase();
        log.info(timeStamp);
        log.info(sign);
        String body = HttpUtil.createGet("https://www.yanjiuchacha.com/api/market/atProduct/useTheNewQueryPageList?pageNo=1&pageSize=150&productType=1&manufacturerId=&productName=&type=")
                .header("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MTY4NjE3NDAsInVzZXJuYW1lIjoiMTU1MTc1Mjg3MjkifQ.UTt2E3-LYYssHUsGv9JXI113OAnr2Vl1ITNnMG3g6GA")
                .header("X-Sign", sign)
                .header("X-TIMESTAMP", timeStamp)
                .execute()
                .body();
        log.info(body);
    }
}
